<?php
/**
  * Musashi - A project manager for music groups and bands
  * Copyright (C) 2010 Daniel Torres
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  */

/**
 *  Controls sql operations over the Costumes table of our database
 *
 *  @author Daniel Torres
 *  @package Musashi
 */

// Make sure we have access to this page
defined('_JEXEC') or die ('Restricted access. Sorry');

// Import the file utilities
jimport('joomla.filesystem.file');

/**
 *  Table definition. Reflects the Song table
 */
class TableCostumes extends JTable
{
    /**
     *  Parameters handled by the actual table
     */
    var $id             = null;
    var $name           = null;
    var $description    = null;
    
    /**
     *  Constructor
     *  All the Musashi table constructors will be similar, except for the table name
     */
    function __construct( &$db )
    {
        parent::__construct('#__Musashi_Costume', 'id', $db);
    }
    
    /**
     *  Commits the information to the database
     */
    function store( $updateNulls = false )
    {
        // Perform the actual store operation first
        if(parent::store($updateNulls))
        {
            // Restore the list of requested pieces, and get the resulting id
            $packedData = $_POST['cid'];
            $unpacked   = explode(",", $packedData);
            $count      = count($unpacked);
            
            // Create a query to insert all values
            $query = "INSERT INTO #__Musashi_Clothing_Costume (idClothing,idCostume) ";
            $start = false;
            $id    = strval($this->_getLastID());
            
            // Remove the old costume
            if( $this->_removeClothingForCostume($this->_getLastID()) == false )
            {
                $app =& JFactory::getApplication();
                $app->enqueueMessage('Warning: Failed to update previous clothing entries');
            }
            
            for( $i = 0; $i < $count; $i++ )
            {
                if( $start ){
                    $query .= " UNION ALL ";
                }
                
                $query .= "SELECT ".strval($unpacked[$i]).",".$id;
                $start = true;
            }
            
            // Insert
            $db =& JFactory::getDBO();
            $db->setQuery( $query );
            if( $db->query() == false )
            {
                $app = &JFactory::getApplication();
                $app->enqueueMessage("Failed to update the costume selection. Error: ".$db->explain());
                return false;
            }
            
            return true;            
        }
        else
        {
            return false;
        }
    }
    
    /**
     *  Deletes a record
     */
    function delete( $oid = null )
    {
        // Make sure anything pointing to this record is deleted
        $this->_removeClothingForCostume($oid);
        
        // Proceed
        return parent::delete($oid);
    }
    
    /**
     *  Returns the right ID for the last added/edited record
     */
    function _getLastID()
    {
        // Either the one stored on the page, or the recently added
        $stored = $_POST['id'];
        
        if( $stored == "" ){
            return mysql_insert_id();
        }
        
        return $stored;
    }
    
    /**
     *  Removes entries on the Clothing/costume table
     *  @param costumeID The id of the costume that is being deleted
     */
    function _removeClothingForCostume( $costumeid )
    {
        $sql = "DELETE 
                FROM #__Musashi_Clothing_Costume
                WHERE #__Musashi_Clothing_Costume.idCostume = ".$costumeid;
                
        $db =& JFactory::getDBO();
        $db->setQuery( $sql );
        return $db->query();
    }
    
}

?>